<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>任务分配</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择员工" prop="userIdList">
              <el-select v-model="form.userIdList" multiple filterable placeholder="请选择员工" style="width:100%">
                <el-option v-for="u in userOptions" :key="u.userId" :label="u.userName" :value="u.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期模式" prop="dateMode">
              <el-radio-group v-model="form.dateMode" @change="handleDateModeChange">
                <el-radio :label="'single'">单日分配</el-radio>
                <el-radio :label="'range'">多日分配</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" v-if="form.dateMode === 'single'">
            <el-form-item label="任务日期" prop="taskDate">
              <el-date-picker v-model="form.taskDate" type="date" placeholder="选择日期" style="width:100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.dateMode === 'range'">
            <el-form-item label="日期范围" prop="dateRange">
              <el-date-picker 
                v-model="form.dateRange" 
                type="daterange" 
                range-separator="至" 
                start-placeholder="开始日期" 
                end-placeholder="结束日期" 
                style="width:100%" 
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>

        </el-row>


        <el-card shadow="never" style="margin-bottom: 16px;">
          <div slot="header" class="clearfix">
            <span>任务明细</span>
            <div style="float:right; display:flex; gap:8px; align-items:center;">
              <el-button type="success" size="mini" icon="el-icon-magic-stick" @click="autoFillTasks">自动填充</el-button>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addRow">手动添加</el-button>
            </div>
          </div>
          
          <!-- 任务选择区域 -->
          <div class="task-selection-area">
            <div class="task-selection-header">
              选择任务：
              <el-button 
                type="text" 
                size="mini" 
                icon="el-icon-refresh" 
                @click="refreshTasks"
                style="margin-left: 8px;"
                :loading="taskLoading"
              >刷新</el-button>
            </div>
            
            <el-row :gutter="16" style="margin-bottom: 12px;">
              <el-col :span="24">
                <el-tooltip :content="submitDisableReason" placement="top" :disabled="canSubmit">
                  <span style="display:block; width:100%">
                    <el-button 
                      type="primary" 
                      size="mini" 
                      icon="el-icon-check" 
                      @click="onSubmit"
                      :disabled="!canSubmit"
                      style="width:100%"
                    >提交</el-button>
                  </span>
                </el-tooltip>
              </el-col>
            </el-row>
            <el-select 
              v-model="selectedTaskIds" 
              multiple 
              filterable 
              placeholder="请选择要分配的任务（可多选）" 
              style="width:100%"
              @visible-change="handleTaskDropdown"
              :popper-append-to-body="true"
              clearable
              no-data-text="暂无可用任务"
              @change="handleTaskSelectionChange"
            >
              <el-option 
                v-for="t in taskOptions" 
                :key="t.id" 
                :label="`${t.title} (${t.description || '无描述'})`" 
                :value="t.id"
              />
            </el-select>
            <!-- 任务明细表格 -->
            <div v-if="form.items && form.items.length > 0" class="task-detail-table">
              <el-table :data="form.items" size="mini" style="width:100%; margin-top: 8px;">
                <el-table-column label="任务" min-width="260">
                  <template slot-scope="{ row, $index }">
                    <el-form-item :prop="`items.${$index}.taskId`" :rules="rules.taskId" label-width="0">
                      <el-select 
                        v-model="row.taskId" 
                        filterable 
                        placeholder="请选择任务" 
                        style="width:100%"
                        :popper-append-to-body="true"
                        clearable
                        no-data-text="暂无可用任务"
                        @change="handleSingleTaskChange"
                      >
                        <el-option v-for="t in taskOptions" :key="t.id" :label="t.title" :value="t.id"/>
                      </el-select>
                    </el-form-item>
                    <div class="desc">{{ getTaskDesc(row.taskId) }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="分数" width="180" align="center">
                  <template slot-scope="{ row, $index }">
                    <el-form-item :prop="`items.${$index}.fraction`" :rules="rules.fraction" label-width="0">
                      <el-input-number 
                        v-model="row.fraction" 
                        :min="0" 
                        :max="100" 
                        :step="1" 
                        :precision="0"
                        @change="handleFractionChange"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template slot-scope="{ $index }">
                    <el-button type="text" icon="el-icon-delete" @click="removeRow($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
           
            <div class="task-selection-info">
              已选择 {{ selectedTaskIds.length }} 个任务，总分：{{ calculateTotalScore() }}
            </div>
          </div>
          
          <!-- 任务明细表格 -->
        </el-card>
        </el-form>
    </el-card>
  </div>
</template>

<script>
/**
 * 绩效考核任务分配组件
 * 
 * 后端接口要求：
 * 1. 需要新增批量查询接口：batchGetAssessByDateRange(params)
 *    - 参数：{ userId, startDate, endDate }
 *    - 返回：包含 taskDate 和 weekday 字段的考核数据数组
 * 
 * 2. 现有的 getAssessByDate 接口保持不变，用于单日查询
 */
import { assignAssessTasks, getAssessUserByUser, getAssessByDate, getExistingByDateRange } from '@/api/system/assessUser'
import { listTask } from '@/api/system/assess'

export default {
  name: 'AssessUserAssign',
  data() {
    return {
      userOptions: [],
      taskOptions: [],
      form: {
        userIdList: [],
        dateMode: 'single', // 'single' 或 'range'
        taskDate: '',
        dateRange: [],
        workdaysOnly: false, // 已废弃，不再过滤工作日
        items: [
          { taskId: null, fraction: 100 }
        ]
      },
      selectedTaskIds: [], // 多选的任务ID列表
      rules: {
        userIdList: [{ required: true, message: '请选择员工', trigger: 'change' }],
        taskDate: [{ required: true, message: '请选择任务日期', trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择日期范围', trigger: 'change' }],
        taskId: [{ required: true, message: '请选择任务', trigger: 'change' }],
        fraction: [{ required: true, message: '请输入任务分数', trigger: 'change' }]
      },
      /* 预览功能已移除：existingItems, existingDateSummary, existingLoading, previewUserId, showDetailView, selectedDate */
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            picker.$emit('pick', [start, end])
          }
        }]
      },
    }
  },
  computed: {
    canSubmit() {
      const hasUsers = this.form.userIdList && this.form.userIdList.length > 0
      const dateOk = this.form.dateMode === 'single' ? !!this.form.taskDate : (this.form.dateRange && this.form.dateRange.length === 2)
      const totalOk = this.calculateTotalScore() === 100
      return hasUsers && dateOk && totalOk
    },
    submitDisableReason() {
      const reasons = []
      if (!this.form.userIdList || this.form.userIdList.length === 0) reasons.push('请选择员工')
      if (this.form.dateMode === 'single') {
        if (!this.form.taskDate) reasons.push('请选择任务日期')
      } else {
        if (!this.form.dateRange || this.form.dateRange.length !== 2) reasons.push('请选择日期范围')
      }
      if (this.calculateTotalScore() !== 100) reasons.push(`总分需为100，当前为 ${this.calculateTotalScore()}`)
      return reasons.length ? reasons.join('；') : '可提交'
    },


    displayDateInfo() {
      if (this.form.dateMode === 'single') {
        return this.form.taskDate
      } else if (this.form.dateRange && this.form.dateRange.length === 2) {
        return `${this.form.dateRange[0]} 至 ${this.form.dateRange[1]}`
      }
      return ''
    },
    selectedUsersOptions() {
      const set = new Set(this.form.userIdList || [])
      return this.userOptions.filter(u => set.has(u.userId))
    }
  },
  created() {
    this.loadUsers()
    // 初次加载全部可用任务（获取最新数据）
    this.loadTasks()
  },
  methods: {
    handleDateModeChange() {
      if (this.form.dateMode === 'single') {
        this.form.dateRange = []
      } else {
        this.form.taskDate = ''
      }
    },
    // 获取日期列表
    getDateList() {
      if (!this.form.dateRange || this.form.dateRange.length !== 2) return []
      
      const startDate = new Date(this.form.dateRange[0])
      const endDate = new Date(this.form.dateRange[1])
      const dates = []
      
      for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
        const dateStr = this.formatDate(d)
        const weekday = d.getDay()
        const isWorkday = weekday !== 0 && weekday !== 6 // 0=周日, 6=周六
        
        dates.push({
          date: dateStr,
          weekday: this.getWeekdayName(weekday),
          isWorkday: isWorkday
        })
      }
      
      return dates
    },
    // 格式化日期为 yyyy-MM-dd
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 获取星期名称
    getWeekdayName(weekday) {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return weekdays[weekday]
    },
    loadUsers() {
      getAssessUserByUser({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.userOptions = (res.rows || []).map(x => ({ userId: x.userId, userName: x.userName }))
      })
    },
    loadTasks() {
      this.taskLoading = true
      // 添加时间戳确保每次都获取最新数据，不使用缓存
      const params = { 
        pageNum: 1, 
        pageSize: 1000, 
        ts: Date.now(),
        _t: new Date().getTime() // 额外的时间戳参数
      }
      
      listTask(params).then(res => {
        const rows = res.rows || []
        this.taskOptions = rows.filter(x => x.state === 0 || x.state === '0')
        
        // 如果当前选中的任务不在新数据中，清空选择
        if (this.selectedTaskIds.length > 0) {
          const validTaskIds = this.taskOptions.map(t => t.id)
          const invalidSelectedIds = this.selectedTaskIds.filter(id => !validTaskIds.includes(id))
          if (invalidSelectedIds.length > 0) {
            this.$message.warning(`以下任务已不可用，已自动移除：${invalidSelectedIds.join(', ')}`)
            this.selectedTaskIds = this.selectedTaskIds.filter(id => validTaskIds.includes(id))
            this.syncTasksToForm()
          }
        }
        
        if (this.taskOptions.length === 0) {
          this.$message.info('暂无可用任务可分配')
        }
      }).catch(() => {
        this.taskOptions = []
        this.$message.error('加载任务失败')
      }).finally(() => {
        this.taskLoading = false
      })
    },
    // 打开下拉时刷新全量列表，确保实时
    handleTaskDropdown(visible) {
      if (visible) {
        // 每次打开下拉都重新加载最新数据
        this.loadTasks()
      }
    },
    
    // 处理多选任务变化
    handleTaskSelectionChange() {
      this.syncTasksToForm()
    },
    
    // 处理单个任务变化
    handleSingleTaskChange() {
      this.syncFormToSelection()
    },
    
    // 处理分数变化
    handleFractionChange() {
      this.syncFormToSelection()
    },
    
    // 自动填充任务
    autoFillTasks() {
      if (this.selectedTaskIds.length === 0) {
        this.$modal.msgWarning('请先选择要分配的任务')
        return
      }
      
      // 清空现有任务
      this.form.items = []
      
      // 平均分配分数
      const avgScore = Math.floor(100 / this.selectedTaskIds.length)
      const remainder = 100 % this.selectedTaskIds.length
      
      this.selectedTaskIds.forEach((taskId, index) => {
        let score = avgScore
        // 将余数分配给前几个任务
        if (index < remainder) {
          score += 1
        }
        
        this.form.items.push({
          taskId: taskId,
          fraction: score
        })
      })
      
      this.$message.success(`已自动填充 ${this.selectedTaskIds.length} 个任务，分数已平均分配`)
    },
    
    // 同步选择的任务到表单
    syncTasksToForm() {
      // 如果选择了任务但表单中没有，则添加
      this.selectedTaskIds.forEach(taskId => {
        const exists = this.form.items.some(item => item.taskId === taskId)
        if (!exists) {
          this.form.items.push({
            taskId: taskId,
            fraction: 0
          })
        }
      })
      
      // 如果表单中有任务但选择中没有，则移除
      this.form.items = this.form.items.filter(item => 
        item.taskId === null || this.selectedTaskIds.includes(item.taskId)
      )
    },
    
    // 同步表单到选择
    syncFormToSelection() {
      const formTaskIds = this.form.items
        .filter(item => item.taskId)
        .map(item => item.taskId)
      
      // 更新选择状态
      this.selectedTaskIds = formTaskIds
    },
    
    // 计算总分
    calculateTotalScore() {
      return this.form.items
        .filter(item => item.taskId)
        .reduce((sum, item) => sum + (Number(item.fraction) || 0), 0)
    },
    
    // 手动刷新任务列表
    refreshTasks() {
      this.loadTasks()
    },
    getTaskDesc(taskId) {
      const t = this.taskOptions.find(x => x.id === taskId)
      return t ? t.description : ''
    },
    addRow() {
      this.form.items.push({ taskId: null, fraction: 100 })
    },
    removeRow(idx) {
      this.form.items.splice(idx, 1)
    },

    onSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        
        // 验证日期
        if (this.form.dateMode === 'single' && !this.form.taskDate) {
          this.$modal.msgWarning('请选择任务日期')
          return
        }
        if (this.form.dateMode === 'range' && (!this.form.dateRange || this.form.dateRange.length !== 2)) {
          this.$modal.msgWarning('请选择日期范围')
          return
        }
        
        // 过滤空行 & 校验重复 taskId
        const cleanItems = this.form.items
          .filter(x => x.taskId)
          .map(x => ({ taskId: x.taskId, fraction: Number(x.fraction) || 0 }))
        if (cleanItems.length === 0) {
          this.$modal.msgWarning('请至少添加一个有效任务')
          return
        }
        const ids = cleanItems.map(x => x.taskId)
        const dup = ids.find((id, idx) => ids.indexOf(id) !== idx)
        if (dup) {
          this.$modal.msgWarning('存在重复任务，请修改后再提交')
          return
        }
        // 校验总分是否为 100
        const total = this.calculateTotalScore()
        if (total !== 100) {
          this.$modal.msgWarning(`分数总和需为 100，当前为 ${total}`)
          return
        }
        
        if (this.form.dateMode === 'single') {
          // 单日分配
        const payload = {
          userIdList: this.form.userIdList,
          taskDate: this.form.taskDate,
          items: cleanItems
        }
          this.executeAssign(payload)
        } else {
          // 多日分配
          const dateList = this.getDateList()
          if (dateList.length === 0) {
            this.$modal.msgWarning('所选日期范围内没有有效的工作日')
            return
          }
          
          // 批量分配
          this.executeBatchAssign(dateList, cleanItems)
        }
      })
    },
    // 执行单日分配
    executeAssign(payload) {
        assignAssessTasks(payload).then(() => {
          this.$modal.msgSuccess('分配成功')
          this.onReset()
        }).catch(err => {
          this.$modal.msgError('分配失败：' + (err.message || '未知错误'))
        })
    },
    // 执行批量分配
    executeBatchAssign(dateList, items) {
      const promises = dateList.map(dateInfo => {
        const payload = {
          userIdList: this.form.userIdList,
          taskDate: dateInfo.date,
          items: items
        }
        return assignAssessTasks(payload)
      })
      
      Promise.all(promises).then(() => {
        this.$modal.msgSuccess(`批量分配成功，共分配 ${dateList.length} 个工作日`)
        this.onReset()
      }).catch(err => {
        this.$modal.msgError('批量分配失败：' + (err.message || '未知错误'))
      })
    },
    
    // 后端批量查询日期范围内的考核数据
    batchGetAssessByDateRange(params) {
      // 调用新的后端批量查询接口
      return getExistingByDateRange(params).then(res => {
        if (res && res.data) {
          return res.data
        }
        return []
      })
    },
    
    // 生成日期汇总数据
    generateDateSummary(data) {
      // 后端已经返回了格式化好的日期汇总数据
      // 直接使用后端数据，但需要确保数据结构一致
      this.existingDateSummary = data.map(item => ({
        date: item.date,
        weekday: item.weekday,
        taskCount: item.taskCount || 0,
        hasData: item.hasData || false,
        items: item.items || []
      }))
    },
    
    // 查看指定日期的详情
    viewDateDetail(date) {
      this.selectedDate = date
      this.showDetailView = true
      this.existingLoading = true
      
      // 查询单日详情
      const uid = this.previewUserId || this.form.userIdList[0]
      getAssessByDate({ date: date, userId: uid }).then(res => {
        const data = res && res.data ? res.data : (Array.isArray(res) ? res : [])
        this.existingItems = Array.isArray(data) ? data : []
      }).catch(() => {
        this.existingItems = []
      }).finally(() => {
        this.existingLoading = false
      })
    },
    
    // 返回汇总视图
    backToSummary() {
      this.showDetailView = false
      this.selectedDate = ''
      this.existingItems = []
    },
    onReset() {
      this.$refs.form.resetFields()
      this.form.dateMode = 'single'
      this.form.taskDate = ''
      this.form.dateRange = []
      this.form.workdaysOnly = false // 已废弃，不再过滤工作日
      this.form.items = [{ taskId: null, fraction: 100 }]
      this.selectedTaskIds = []
      this.existingItems = []
      this.existingDateSummary = []
      this.previewUserId = null
      this.showDetailView = false
      this.selectedDate = ''
      // 重置后重新加载一次全部任务
      this.loadTasks()
    },
  }
}
</script>

<style scoped>
.desc {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.task-selection-area {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.task-selection-header {
  margin-bottom: 8px;
  font-weight: bold;
  color: #606266;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.task-selection-info {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  padding: 4px 8px;
  background-color: #fff;
  border-radius: 3px;
  border: 1px solid #e9ecef;
}

.task-detail-table {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}
</style> 